import {
  Box,
  Button,
  Flex,
  Heading,
  SimpleGrid,
  Spinner,
  Stack,
  Text,
  useToast,
} from '@chakra-ui/react';
import { Link as RouterLink } from 'react-router-dom';
import { useEffect, useState } from 'react';
import ProductCard from '../components/home/ProductCard';
import { fetchCatalogItems, type CatalogItem } from '../lib/api';
import { useCart } from '../hooks/useCart';

const ProductPage = () => {
  const [items, setItems] = useState<CatalogItem[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);
  const { addItem } = useCart();
  const toast = useToast();

  useEffect(() => {
    let cancelled = false;

    const load = async () => {
      setLoading(true);
      setError(null);
      try {
        const data = await fetchCatalogItems();
        if (!cancelled) {
          setItems(data);
        }
      } catch (err) {
        if (!cancelled) {
          setError(err instanceof Error ? err.message : 'Failed to load catalog');
        }
      } finally {
        if (!cancelled) {
          setLoading(false);
        }
      }
    };

    void load();
    return () => {
      cancelled = true;
    };
  }, []);

  const handleAddToCart = async (product: CatalogItem) => {
    await addItem({
      productId: String(product.id),
      productName: product.name,
      unitPrice: product.price,
    });
    toast({
      title: `${product.name} added to cart`,
      status: 'success',
      duration: 2000,
      isClosable: true,
    });
  };

  return (
    <Stack spacing={4}>
      <Flex justify="space-between" align={{ base: 'flex-start', md: 'center' }} direction={{ base: 'column', md: 'row' }}>
        <Heading size="lg">Product Catalog</Heading>
        {error && (
          <Text color="orange.500" fontSize="sm">
            {error}
          </Text>
        )}
      </Flex>

      {loading ? (
        <Flex align="center" justify="center" py={12} bg="white" borderRadius="2xl" border="1px solid" borderColor="gray.200">
          <Spinner size="lg" color="brand.500" />
        </Flex>
      ) : (
        <Box bg="white" borderRadius="2xl" border="1px solid" borderColor="gray.200" p={6}>
          <SimpleGrid columns={{ base: 1, sm: 2, md: 3 }} spacing={4}>
            {items.map((product) => (
              <Stack key={product.id} spacing={3} border="1px solid" borderColor="gray.100" rounded="xl" p={4}>
                <ProductCard product={product} showViewButton={false} />
                <Button
                  colorScheme="brand"
                  onClick={() => void handleAddToCart(product)}
                  isDisabled={typeof product.price !== 'number'}
                >
                  Add to Cart
                </Button>
                <Button as={RouterLink} to={`/product/${product.id}`} variant="link" colorScheme="gray">
                  View details
                </Button>
              </Stack>
            ))}
          </SimpleGrid>
        </Box>
      )}
    </Stack>
  );
};

export default ProductPage;
